package com.szholly.data.common.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.szholly.utils.spring.SpringBeanFactory;
import com.szholly.utils.util.TreeDataNode;
import com.szholly.data.cache.MetadataDataCache;
import com.szholly.data.general.ITable;
import com.szholly.data.general.IWorkspace;
import com.szholly.data.general.IWorkspaceFactory;
import com.szholly.data.general.TableType;

/**
 * 定义表处理辅助类
 */
public class TablesUtils {
	
	/**
	 * 获取数据库中的原始数据表
	 * @return
	 */
	public static List<Map<String, String>> getBaseTables() {
		
		IWorkspaceFactory workspaceFactory = (IWorkspaceFactory) SpringBeanFactory
				.getBean("WorkspaceFactory");
		IWorkspace pWorkspace = workspaceFactory.openWorkspace();
		String[] tableNames = pWorkspace.getObjects(TableType.Table);
		
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		for(String tableName : tableNames){
			Map<String, String> result = new HashMap<String, String>();
			result.put("id", tableName);
			result.put("text", tableName);
			list.add(result);
		}
		
		return list;
	}
	
	/**
	 * 获取当前的所有表信息，以树的形式展示
	 * @return
	 */
	public static List<TreeDataNode> getTables() {
		HashMap<String, ITable> tableCache = MetadataDataCache.getTableCache();
		Set<String> keys = tableCache.keySet();
		List<TreeDataNode> result = new ArrayList<TreeDataNode>();
		HashMap<String, TreeDataNode> treeGroup = new HashMap<String, TreeDataNode>();
		for (String key : keys) {
			ITable pTable = tableCache.get(key);
			String groupKey = pTable.getTableGroup();
			TreeDataNode pTableNode = null;
			if (treeGroup.containsKey(groupKey)) {
				pTableNode = treeGroup.get(groupKey);
			} else {
				pTableNode = new TreeDataNode();
				pTableNode.setid(groupKey);
				pTableNode.setText(groupKey);
				result.add(pTableNode);
				pTableNode.setChildren(new ArrayList<TreeDataNode>());
				treeGroup.put(groupKey, pTableNode);
			}
			TreeDataNode tableNode = new TreeDataNode();
			tableNode.setid(pTable.getMetadataTableName());
			tableNode.setText(pTable.getMetadataTableAliasName());
			tableNode.setState("open");
			pTableNode.getChildren().add(tableNode);
		}
		return result;
	}

	/**
	 * 获取表信息
	 * @return
	 */
	public static HashMap<String, String> getTablesMap(){
		HashMap<String, ITable> tableCache = MetadataDataCache.getTableCache();
		Set<String> keys = tableCache.keySet();
		HashMap<String, String> result = new LinkedHashMap<String, String>();
		for (String key : keys) {
			ITable pTable = tableCache.get(key);
			result.put(key, pTable.getMetadataTableAliasName());
		}
		return result;
	}
}